{% extends "base.html" %}
{% load static %}

{% block title %}报表设计器{% endblock %}

{% block extra_css %}
<link href="{% static 'css/analytics.css' %}" rel="stylesheet">
<style>
.designer-container {
    height: calc(100vh - 120px);
    display: flex;
}

.designer-sidebar {
    width: 300px;
    background: #f8f9fa;
    border-right: 1px solid #dee2e6;
    overflow-y: auto;
}

.designer-main {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.designer-toolbar {
    background: white;
    border-bottom: 1px solid #dee2e6;
    padding: 10px 20px;
}

.designer-canvas {
    flex: 1;
    background: white;
    position: relative;
    overflow: auto;
}

.config-section {
    border-bottom: 1px solid #dee2e6;
    padding: 15px;
}

.config-section:last-child {
    border-bottom: none;
}

.config-section h6 {
    margin-bottom: 10px;
    color: #495057;
    font-weight: 600;
}

.field-item {
    padding: 8px 12px;
    margin: 5px 0;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
}

.field-item:hover {
    background: #e9ecef;
    border-color: #007bff;
}

.field-item.selected {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

.chart-preview {
    min-height: 400px;
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px;
}

.filter-builder {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
}

.filter-row {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.filter-row:last-child {
    margin-bottom: 0;
}

.btn-remove-filter {
    color: #dc3545;
    border: none;
    background: none;
    padding: 5px;
}

.data-preview {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #dee2e6;
    border-radius: 4px;
}

.preview-table {
    font-size: 0.875rem;
}

.preview-table th {
    background: #f8f9fa;
    position: sticky;
    top: 0;
    z-index: 1;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid p-0">
    <!-- 顶部工具栏 -->
    <div class="designer-toolbar d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">
                <i class="fas fa-chart-line text-primary"></i>
                {% if template %}编辑报表: {{ template.name }}{% else %}创建新报表{% endif %}
            </h5>
        </div>
        <div>
            <button class="btn btn-outline-secondary" onclick="previewReport()">
                <i class="fas fa-eye"></i> 预览
            </button>
            <button class="btn btn-success" onclick="saveReport()">
                <i class="fas fa-save"></i> 保存
            </button>
            <a href="{% url 'assets:report_list' %}" class="btn btn-outline-primary">
                <i class="fas fa-arrow-left"></i> 返回
            </a>
        </div>
    </div>

    <div class="designer-container">
        <!-- 左侧配置面板 -->
        <div class="designer-sidebar">
            <!-- 基本信息 -->
            <div class="config-section">
                <h6><i class="fas fa-info-circle"></i> 基本信息</h6>
                <div class="mb-3">
                    <label class="form-label">报表名称</label>
                    <input type="text" class="form-control" id="reportName" 
                           value="{% if template %}{{ template.name }}{% endif %}" placeholder="输入报表名称">
                </div>
                <div class="mb-3">
                    <label class="form-label">描述</label>
                    <textarea class="form-control" id="reportDescription" rows="2" 
                              placeholder="输入报表描述">{% if template %}{{ template.description }}{% endif %}</textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">报表类型</label>
                    <select class="form-select" id="reportType">
                        {% for choice in report_types %}
                        <option value="{{ choice.0 }}" 
                                {% if template and template.report_type == choice.0 %}selected{% endif %}>
                            {{ choice.1 }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">图表类型</label>
                    <select class="form-select" id="chartType">
                        <option value="">选择图表类型</option>
                        {% for choice in chart_types %}
                        <option value="{{ choice.0 }}" 
                                {% if template and template.chart_type == choice.0 %}selected{% endif %}>
                            {{ choice.1 }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="isPublic" 
                           {% if template and template.is_public %}checked{% endif %}>
                    <label class="form-check-label" for="isPublic">
                        公开报表
                    </label>
                </div>
            </div>

            <!-- 数据源配置 -->
            <div class="config-section">
                <h6><i class="fas fa-database"></i> 数据源</h6>
                <div class="mb-3">
                    <label class="form-label">选择数据源</label>
                    <select class="form-select" id="dataSource" onchange="loadDataSourceFields()">
                        <option value="">选择数据源</option>
                        <option value="asset">资产</option>
                        <option value="maintenance">维修记录</option>
                        <option value="category">资产类别</option>
                        <option value="department">部门</option>
                    </select>
                </div>
                
                <!-- 字段列表 -->
                <div id="fieldsContainer" style="display: none;">
                    <label class="form-label">可用字段</label>
                    <div id="fieldsList"></div>
                </div>
            </div>

            <!-- 查询配置 -->
            <div class="config-section">
                <h6><i class="fas fa-filter"></i> 查询配置</h6>
                
                <!-- 过滤条件 -->
                <div class="mb-3">
                    <label class="form-label">过滤条件</label>
                    <div id="filtersContainer">
                        <!-- 过滤条件将动态添加到这里 -->
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addFilter()">
                        <i class="fas fa-plus"></i> 添加条件
                    </button>
                </div>

                <!-- 聚合配置 -->
                <div class="mb-3">
                    <label class="form-label">聚合方式</label>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="enableAggregation" 
                               onchange="toggleAggregation()">
                        <label class="form-check-label" for="enableAggregation">
                            启用聚合
                        </label>
                    </div>
                    <div id="aggregationConfig" style="display: none;">
                        <div class="mt-2">
                            <label class="form-label">分组字段</label>
                            <select class="form-select" id="groupByField">
                                <option value="">选择分组字段</option>
                            </select>
                        </div>
                        <div class="mt-2">
                            <label class="form-label">聚合函数</label>
                            <select class="form-select" id="aggregateFunction">
                                <option value="count">计数</option>
                                <option value="sum">求和</option>
                                <option value="avg">平均值</option>
                                <option value="max">最大值</option>
                                <option value="min">最小值</option>
                            </select>
                        </div>
                        <div class="mt-2">
                            <label class="form-label">聚合字段</label>
                            <select class="form-select" id="aggregateField">
                                <option value="">选择聚合字段</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- 排序和限制 -->
                <div class="mb-3">
                    <label class="form-label">排序字段</label>
                    <select class="form-select" id="orderByField">
                        <option value="">选择排序字段</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">记录限制</label>
                    <input type="number" class="form-control" id="recordLimit" 
                           placeholder="最大记录数" min="1" max="10000">
                </div>
            </div>

            <!-- 图表配置 -->
            <div class="config-section" id="chartConfig" style="display: none;">
                <h6><i class="fas fa-chart-bar"></i> 图表配置</h6>
                <div class="mb-3">
                    <label class="form-label">X轴字段</label>
                    <select class="form-select" id="xAxisField">
                        <option value="">选择X轴字段</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Y轴字段</label>
                    <select class="form-select" id="yAxisField">
                        <option value="">选择Y轴字段</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">图表标题</label>
                    <input type="text" class="form-control" id="chartTitle" placeholder="输入图表标题">
                </div>
            </div>
        </div>

        <!-- 主要设计区域 -->
        <div class="designer-main">
            <div class="designer-canvas">
                <!-- 数据预览 -->
                <div class="m-3">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6><i class="fas fa-table"></i> 数据预览</h6>
                        <button class="btn btn-sm btn-outline-primary" onclick="refreshPreview()">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                    </div>
                    <div id="dataPreview" class="data-preview">
                        <div class="text-center py-4 text-muted">
                            <i class="fas fa-database fa-2x mb-2"></i>
                            <p>请先选择数据源</p>
                        </div>
                    </div>
                </div>

                <!-- 图表预览 -->
                <div class="m-3">
                    <h6><i class="fas fa-chart-line"></i> 图表预览</h6>
                    <div class="chart-preview">
                        <div id="chartContainer">
                            <div class="text-center text-muted">
                                <i class="fas fa-chart-bar fa-3x mb-3"></i>
                                <p>配置完成后将显示图表预览</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 保存确认模态框 -->
<div class="modal fade" id="saveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">保存报表</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要保存这个报表吗？</p>
                <div id="saveValidationErrors" class="alert alert-danger" style="display: none;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="confirmSave()">确定保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 全局变量
let dataSourceFields = {{ data_sources|safe }};
let currentChart = null;
let filterCount = 0;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    {% if template %}
    // 如果是编辑模式，加载现有配置
    loadExistingTemplate();
    {% endif %}
    
    // 绑定事件
    document.getElementById('chartType').addEventListener('change', toggleChartConfig);
    document.getElementById('dataSource').addEventListener('change', loadDataSourceFields);
});

// 加载现有模板配置
function loadExistingTemplate() {
    {% if template %}
    const template = {{ template|safe }};
    
    // 设置数据源
    document.getElementById('dataSource').value = '{{ template.data_source }}';
    loadDataSourceFields();
    
    // 设置查询配置
    const queryConfig = {{ template.query_config|safe }};
    if (queryConfig.filters) {
        queryConfig.filters.forEach(filter => {
            addFilter(filter);
        });
    }
    
    // 设置报表配置
    const reportConfig = {{ template.report_config|safe }};
    if (reportConfig.x_field) {
        document.getElementById('xAxisField').value = reportConfig.x_field;
    }
    if (reportConfig.y_field) {
        document.getElementById('yAxisField').value = reportConfig.y_field;
    }
    if (reportConfig.title) {
        document.getElementById('chartTitle').value = reportConfig.title;
    }
    
    toggleChartConfig();
    {% endif %}
}

// 加载数据源字段
function loadDataSourceFields() {
    const dataSource = document.getElementById('dataSource').value;
    const fieldsContainer = document.getElementById('fieldsContainer');
    const fieldsList = document.getElementById('fieldsList');
    
    if (!dataSource) {
        fieldsContainer.style.display = 'none';
        return;
    }
    
    fieldsContainer.style.display = 'block';
    
    // 查找对应的数据源
    const sourceData = dataSourceFields.find(ds => ds.key === dataSource);
    if (!sourceData) return;
    
    // 清空现有字段
    fieldsList.innerHTML = '';
    
    // 添加字段
    sourceData.fields.forEach(field => {
        const fieldItem = document.createElement('div');
        fieldItem.className = 'field-item';
        fieldItem.innerHTML = `
            <div class="d-flex justify-content-between align-items-center">
                <span>${field.label}</span>
                <small class="text-muted">${field.type}</small>
            </div>
            <small class="text-muted">${field.name}</small>
        `;
        fieldItem.onclick = () => selectField(field, fieldItem);
        fieldsList.appendChild(fieldItem);
    });
    
    // 更新下拉选项
    updateFieldSelects(sourceData.fields);
    
    // 刷新数据预览
    refreshPreview();
}

// 更新字段选择下拉框
function updateFieldSelects(fields) {
    const selects = ['groupByField', 'aggregateField', 'orderByField', 'xAxisField', 'yAxisField'];
    
    selects.forEach(selectId => {
        const select = document.getElementById(selectId);
        const currentValue = select.value;
        
        // 清空选项
        select.innerHTML = '<option value="">选择字段</option>';
        
        // 添加字段选项
        fields.forEach(field => {
            const option = document.createElement('option');
            option.value = field.name;
            option.textContent = field.label;
            select.appendChild(option);
        });
        
        // 恢复之前的选择
        if (currentValue) {
            select.value = currentValue;
        }
    });
}

// 选择字段
function selectField(field, element) {
    // 移除其他选中状态
    document.querySelectorAll('.field-item').forEach(item => {
        item.classList.remove('selected');
    });
    
    // 添加选中状态
    element.classList.add('selected');
    
    console.log('Selected field:', field);
}

// 切换图表配置显示
function toggleChartConfig() {
    const chartType = document.getElementById('chartType').value;
    const chartConfig = document.getElementById('chartConfig');
    
    if (chartType && chartType !== '') {
        chartConfig.style.display = 'block';
    } else {
        chartConfig.style.display = 'none';
    }
}

// 切换聚合配置
function toggleAggregation() {
    const enabled = document.getElementById('enableAggregation').checked;
    const config = document.getElementById('aggregationConfig');
    
    config.style.display = enabled ? 'block' : 'none';
}

// 添加过滤条件
function addFilter(existingFilter = null) {
    filterCount++;
    const container = document.getElementById('filtersContainer');
    
    const filterRow = document.createElement('div');
    filterRow.className = 'filter-row';
    filterRow.id = `filter-${filterCount}`;
    
    filterRow.innerHTML = `
        <select class="form-select" style="flex: 1;">
            <option value="">选择字段</option>
        </select>
        <select class="form-select" style="flex: 0 0 120px;">
            <option value="equals">等于</option>
            <option value="contains">包含</option>
            <option value="greater_than">大于</option>
            <option value="less_than">小于</option>
            <option value="between">介于</option>
        </select>
        <input type="text" class="form-control" placeholder="值" style="flex: 1;">
        <button type="button" class="btn-remove-filter" onclick="removeFilter('filter-${filterCount}')">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    container.appendChild(filterRow);
    
    // 更新字段选项
    const dataSource = document.getElementById('dataSource').value;
    if (dataSource) {
        const sourceData = dataSourceFields.find(ds => ds.key === dataSource);
        if (sourceData) {
            const fieldSelect = filterRow.querySelector('select');
            sourceData.fields.forEach(field => {
                const option = document.createElement('option');
                option.value = field.name;
                option.textContent = field.label;
                fieldSelect.appendChild(option);
            });
            
            // 如果有现有过滤条件，设置值
            if (existingFilter) {
                fieldSelect.value = existingFilter.field;
                filterRow.querySelector('select:nth-child(2)').value = existingFilter.operator;
                filterRow.querySelector('input').value = existingFilter.value;
            }
        }
    }
}

// 移除过滤条件
function removeFilter(filterId) {
    const filterRow = document.getElementById(filterId);
    if (filterRow) {
        filterRow.remove();
    }
}

// 刷新数据预览
function refreshPreview() {
    const dataSource = document.getElementById('dataSource').value;
    if (!dataSource) {
        document.getElementById('dataPreview').innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="fas fa-database fa-2x mb-2"></i>
                <p>请先选择数据源</p>
            </div>
        `;
        return;
    }
    
    // 构建查询配置
    const queryConfig = buildQueryConfig();
    
    // 显示加载状态
    document.getElementById('dataPreview').innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2 text-muted">正在加载数据...</p>
        </div>
    `;
    
    // 获取数据预览
    const params = new URLSearchParams({
        data_source: dataSource,
        query_config: JSON.stringify(queryConfig)
    });
    
    fetch(`/assets/analytics/api/preview-data/?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayDataPreview(data.data);
            } else {
                document.getElementById('dataPreview').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i>
                        ${data.message || '数据加载失败'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('dataPreview').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    数据加载失败
                </div>
            `;
        });
}

// 显示数据预览
function displayDataPreview(data) {
    const container = document.getElementById('dataPreview');
    
    if (!data || (Array.isArray(data.data) && data.data.length === 0)) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="fas fa-inbox fa-2x mb-2"></i>
                <p>没有找到匹配的数据</p>
            </div>
        `;
        return;
    }
    
    let tableData = data.data;
    if (!Array.isArray(tableData)) {
        // 如果是单个对象，转换为数组
        tableData = [tableData];
    }
    
    if (tableData.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="fas fa-inbox fa-2x mb-2"></i>
                <p>没有找到匹配的数据</p>
            </div>
        `;
        return;
    }
    
    // 获取列名
    const columns = Object.keys(tableData[0]);
    
    // 构建表格
    let tableHtml = `
        <table class="table table-sm preview-table">
            <thead>
                <tr>
                    ${columns.map(col => `<th>${col}</th>`).join('')}
                </tr>
            </thead>
            <tbody>
    `;
    
    // 只显示前50行
    const displayData = tableData.slice(0, 50);
    displayData.forEach(row => {
        tableHtml += '<tr>';
        columns.forEach(col => {
            let value = row[col];
            if (value === null || value === undefined) {
                value = '-';
            } else if (typeof value === 'object') {
                value = JSON.stringify(value);
            }
            tableHtml += `<td>${value}</td>`;
        });
        tableHtml += '</tr>';
    });
    
    tableHtml += `
            </tbody>
        </table>
    `;
    
    if (tableData.length > 50) {
        tableHtml += `<div class="text-center text-muted p-2">显示前50条记录，共${tableData.length}条</div>`;
    }
    
    container.innerHTML = tableHtml;
}

// 构建查询配置
function buildQueryConfig() {
    const config = {};
    
    // 过滤条件
    const filters = [];
    document.querySelectorAll('.filter-row').forEach(row => {
        const field = row.querySelector('select').value;
        const operator = row.querySelector('select:nth-child(2)').value;
        const value = row.querySelector('input').value;
        
        if (field && operator && value) {
            filters.push({ field, operator, value });
        }
    });
    
    if (filters.length > 0) {
        config.filters = filters;
    }
    
    // 聚合配置
    if (document.getElementById('enableAggregation').checked) {
        const groupBy = document.getElementById('groupByField').value;
        const aggregateFunction = document.getElementById('aggregateFunction').value;
        const aggregateField = document.getElementById('aggregateField').value;
        
        if (groupBy && aggregateFunction) {
            config.aggregation = {
                group_by: [groupBy],
                metrics: [{
                    field: aggregateField || 'id',
                    function: aggregateFunction,
                    alias: `${aggregateFunction}_${aggregateField || 'count'}`
                }]
            };
        }
    }
    
    // 排序
    const orderBy = document.getElementById('orderByField').value;
    if (orderBy) {
        config.order_by = [orderBy];
    }
    
    // 限制
    const limit = document.getElementById('recordLimit').value;
    if (limit) {
        config.limit = parseInt(limit);
    }
    
    return config;
}

// 预览报表
function previewReport() {
    const reportConfig = buildReportConfig();
    
    if (!reportConfig.data_source) {
        showAlert('warning', '请先选择数据源');
        return;
    }
    
    // 显示加载状态
    const chartContainer = document.getElementById('chartContainer');
    chartContainer.innerHTML = `
        <div class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">生成中...</span>
            </div>
            <p class="mt-2 text-muted">正在生成图表...</p>
        </div>
    `;
    
    // 创建临时模板并执行
    fetch('/assets/analytics/api/execute-temp-report/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(reportConfig)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && data.chart_config) {
            renderChart(data.chart_config);
        } else {
            chartContainer.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    ${data.error || '图表生成失败'}
                </div>
            `;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        chartContainer.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i>
                图表生成失败
            </div>
        `;
    });
}

// 渲染图表
function renderChart(chartConfig) {
    const chartContainer = document.getElementById('chartContainer');
    
    // 清除现有图表
    if (currentChart) {
        currentChart.destroy();
    }
    
    // 创建canvas元素
    chartContainer.innerHTML = '<canvas id="previewChart" width="400" height="200"></canvas>';
    
    const ctx = document.getElementById('previewChart').getContext('2d');
    currentChart = new Chart(ctx, chartConfig);
}

// 构建报表配置
function buildReportConfig() {
    const config = {
        name: document.getElementById('reportName').value,
        description: document.getElementById('reportDescription').value,
        report_type: document.getElementById('reportType').value,
        chart_type: document.getElementById('chartType').value,
        data_source: document.getElementById('dataSource').value,
        is_public: document.getElementById('isPublic').checked,
        query_config: buildQueryConfig(),
        report_config: {
            x_field: document.getElementById('xAxisField').value,
            y_field: document.getElementById('yAxisField').value,
            title: document.getElementById('chartTitle').value
        }
    };
    
    {% if template %}
    config.template_id = {{ template.id }};
    {% endif %}
    
    return config;
}

// 保存报表
function saveReport() {
    const config = buildReportConfig();
    
    // 验证必填字段
    const errors = [];
    if (!config.name) errors.push('请输入报表名称');
    if (!config.report_type) errors.push('请选择报表类型');
    if (!config.data_source) errors.push('请选择数据源');
    
    if (errors.length > 0) {
        document.getElementById('saveValidationErrors').innerHTML = errors.join('<br>');
        document.getElementById('saveValidationErrors').style.display = 'block';
        new bootstrap.Modal(document.getElementById('saveModal')).show();
        return;
    }
    
    document.getElementById('saveValidationErrors').style.display = 'none';
    new bootstrap.Modal(document.getElementById('saveModal')).show();
}

// 确认保存
function confirmSave() {
    const config = buildReportConfig();
    
    fetch('/assets/analytics/reports/save/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('saveModal')).hide();
            
            // 跳转到报表查看页面
            setTimeout(() => {
                window.location.href = `/assets/analytics/reports/${data.template_id}/`;
            }, 1000);
        } else {
            showAlert('danger', data.message || '保存失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', '保存失败');
    });
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}
</script>
{% endblock %}